//
//  YMYOneSelectField.swift
//  NewsHuBei
//
//  Created by 虞明义 on 2017/11/29.
//  Copyright © 2017年 yumingyi. All rights reserved.
//

import UIKit

@objc protocol YMYOneSelectFieldDelegate:NSObjectProtocol {
    func selectField(field:YMYOneSelectField,indexInDatas:Int)->String?
  @objc optional func selectField(field:YMYOneSelectField,selectIndexOfDatas:Int)
}

protocol YMYOneSelectFieldDataSource:NSObjectProtocol {
    func selectField(field:YMYOneSelectField)->Int
}


class YMYOneSelectField: UIView {

    weak var delegate:YMYOneSelectFieldDelegate?
    weak var dataSource:YMYOneSelectFieldDataSource?
    
    
    /// 默认空数据，因为都从网络获取，这里默认空数据
    fileprivate lazy var isEmptyData:Bool = true
    
    var font:UIFont = UIFont.systemFont(ofSize: 14){
        didSet{
            titelLabel.font = font
        }
    }
    
    var text:String?{
        set{
            titelLabel.text = newValue
        }
        get{
            return titelLabel.text
        }
    }
    
    var textColor:UIColor?{
        set{
            titelLabel.textColor = newValue
        }
        get{
            return titelLabel.textColor
        }
    }
    
    lazy var emptyView:UILabel = {
        let lab = UILabel.init()
        lab.text = "no data"
        lab.textAlignment = .center
        lab.backgroundColor = UIColor.groupTableViewBackground
        return lab
    }()
    
    init() {
        super.init(frame: CGRect.zero)
        setUp()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 注释:初始化UI************
    private func setUp(){
        addSubview(textF)
        textF.isHidden = true
        addSubview(titelLabel)
        
        pickView.addSubview(emptyView)
        emptyView.backgroundColor = pickView.backgroundColor
        textF.inputView = pickView
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(showKeyBoardAction))
        titelLabel.addGestureRecognizer(tap)
    }
    //MARK: - 注释:加载数据**************
    
    //MARK: - 注释:点击事件**************
    @objc fileprivate func showKeyBoardAction(tap:UITapGestureRecognizer){
        textF.becomeFirstResponder()
    }
    //MARK: - 注释:数据请求**************
    
    //MARK: - 注释:业务逻辑**************
    @objc fileprivate func keyboardWillHidden(noti:NotificationCenter){
        if !textF.isFirstResponder{
            return
        }
        if isEmptyData{
            emptyView.isHidden = false
            return
        }else{
            let row = pickView.selectedRow(inComponent: 0)
            let text = delegate?.selectField(field: self, indexInDatas: row)
            titelLabel.text = text
            if delegate != nil && delegate!.responds(to:#selector(delegate?.selectField(field:selectIndexOfDatas:))) == true{
                 delegate!.selectField!(field: self, selectIndexOfDatas: row)
            }
        }
    }
    
    @objc fileprivate func keyboardWillShow(noti:NotificationCenter){
        if !textF.isFirstResponder{
            return
        }
        emptyView.isHidden = !isEmptyData
        emptyView.frame = pickView.bounds
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        textF.rightView = sanJiaoView
        textF.rightViewMode = .always
        textF.frame = bounds
        titelLabel.frame = bounds
    }
    
    func reloadData(){
        emptyView.isHidden = dataSource?.selectField(field: self) != 0
        pickView.reloadAllComponents()
    }
    

    //MARK: - 注释:代理方法**************
    
    //MARK: - 注释:通知注册和销毁**************
    fileprivate lazy var titelLabel:UILabel = {
        let lab = UILabel.init()
        lab.textAlignment = .center
        lab.isUserInteractionEnabled = true
        return lab
    }()

    fileprivate lazy var textF:UITextField = {
        let tx = UITextField.init()
        tx.font = UIFont.systemFont(ofSize: 12)
        tx.borderStyle = .roundedRect
        tx.textColor = UIColor.init(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1)
        tx.backgroundColor = UIColor.groupTableViewBackground
        return tx
    }()
    
    fileprivate lazy var pickView:UIPickerView = {
        [unowned self] in
        let pick = UIPickerView.init()
        pick.delegate = self
        pick.dataSource = self
        return pick
        }()
    
    fileprivate lazy var sanJiaoView:UIImageView = {
        UIGraphicsBeginImageContext(CGSize.init(width: 6, height: 10))
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(UIColor.black.cgColor)
        context?.beginPath()
        context?.move(to: CGPoint.init(x: 0, y: 0))
        context?.addLine(to: CGPoint.init(x: 3, y: 10))
        context?.addLine(to: CGPoint.init(x: 6, y: 0))
        context?.closePath()
        context?.fillPath()
        let img = UIGraphicsGetImageFromCurrentImageContext()
        let imgV = UIImageView.init(image: img)
        return imgV
    }()
}

extension YMYOneSelectField:UIPickerViewDelegate,UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if dataSource == nil || dataSource?.selectField(field: self) == 0{
            isEmptyData = true
            return 0
        }else{
            isEmptyData = false
            return dataSource?.selectField(field: self) ?? 0
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let lab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 40))
        lab.font = font
        lab.textColor = UIColor.init(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1)
        lab.textAlignment = .center
        lab.text = delegate?.selectField(field: self, indexInDatas: row)
        return lab
    }
}
